﻿using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;

namespace Glorysoft.EAP.RC.EAPClient
{
    public class MSAccessHelper
    {
        private readonly Logger CimLogger;
        private string sPath;
        public MSAccessHelper()
        {
            CimLogger = XfwContext.LogManager.EapLogger;
          //  Init();
        }

        /// <summary>
        /// FP3000 针卡查询
        /// </summary>
        /// <param name="Location"></param>
        /// <param name="CardID"></param>
        /// <param name="ProductID"></param>
        /// <returns></returns>
        public string MSAccessConnect(string Location, string CardID, string ProductID)
        {
            try
            {        
                var result = "";
                var msg = "";
                var dataSource = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Dict.Current.DataSource + ";max pool size=5;Mode=Read";
                IFreeSql fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MsAccess, dataSource).UseAutoSyncStructure(true).Build();  //自动同步实体结构到数据库
                bool isAvailable = fsql.Ado.MasterPool.IsAvailable;
                if (isAvailable)
                {
                    result = MSAccessByFP3000(fsql, Location, CardID, ProductID);
                }
                else
                {
                    for (int i = 0; i < 11; i++)
                    {
                        Thread.Sleep(5000);//延迟5s查询
                        IFreeSql fsqlstatus = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MsAccess, dataSource).UseAutoSyncStructure(true).Build();
                        if (fsqlstatus.Ado.MasterPool.IsAvailable)
                        {
                            result = MSAccessByFP3000(fsqlstatus, Location, CardID, ProductID);
                            break;
                        }
                        else
                        {
                            msg = fsqlstatus.Ado.MasterPool.UnavailableException.Message;
                            result = "访问针卡数据库失败,请联系针卡系统工程师进行检查! ";
                        }
                    }
                }
                CimLogger.Warning($"{GetType().Name}.MSAccessConnect() 查询数据失败，{msg}，Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                return result;    
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}.MSAccessConnect: {ex}");
                return "EAP->ProberCard System Verification failed！";
            }

        }
        /// <summary>
        /// UF2000 UF200 Uf200R 针卡查询
        /// </summary>
        /// <param name="Location"></param>
        /// <param name="CardID"></param>
        /// <param name="ProductID"></param>
        /// <returns></returns>
        public string MSAccessConnectQuery(string Location, string CardID, string ProductID)
        {
            try
            {

                var result = "";
                var msg = "";               
                var dataSource = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Dict.Current.DataSource + ";max pool size=5;Mode=Read";
                IFreeSql fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MsAccess, dataSource).UseAutoSyncStructure(true).Build();  //自动同步实体结构到数据库
                bool isAvailable = fsql.Ado.MasterPool.IsAvailable;
                if (isAvailable)
                {
                    result= MSAccessByUF2000(fsql,  Location,  CardID, ProductID);
                }
                else
                {                
                    for (int i = 0; i < 11; i++)
                    {
                        Thread.Sleep(5000);//延迟5s查询
                        IFreeSql fsqlstatus = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MsAccess, dataSource).UseAutoSyncStructure(true).Build();
                        if (fsqlstatus.Ado.MasterPool.IsAvailable)
                        {
                            result = MSAccessByUF2000(fsqlstatus, Location, CardID, ProductID);
                            break;
                        }
                        else
                        {
                            msg = fsqlstatus.Ado.MasterPool.UnavailableException.Message;
                            result = "访问针卡数据库失败,请联系针卡系统工程师进行检查! ";
                        }                      
                    }       
                }               
                CimLogger.Warning($"{GetType().Name}.MSAccessConnect() 查询数据失败，{msg}，Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                fsql.Dispose();
                return result;
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}.MSAccessConnect: {ex}");
                return "EAP->ProberCard System Verification failed！";
            }

        }


        public string MSAccessByFP3000(IFreeSql fsql, string Location, string CardID, string ProductID)
        {
            var result = "";
            var return_result = fsql.Ado.Query<ProberCardList>("SELECT  a.[ProductID], a.[CardID] ,a.[Location],a.[CardStatus] FROM [ProbeCardList] a " + "where a.CardID=" + "'" + CardID + "'" + " " + "and a.Location=" + "'" + Location + "'");
            if (return_result.Count != 0 && return_result.Count == 1)
            {
                CimLogger.Debug($"{GetType().Name}.MSAccessConnect() 查询数据成功");
                if (ProductID.Length >= 4)
                {
                    var productid = ProductID.Substring(0, 4);
                    if (return_result[0].ProductID.Contains(productid))
                    {
                        if (return_result[0].CardStatus == "Work")
                        {
                            result = "success";
                            var messagess = TranslateMsg.GetTranslation("ProbeCardValidationOK");
                            if (messagess != null && messagess.Count != 0)
                            {
                                EAPClientService ClientService = new EAPClientService();
                                ClientService.ShowMessage(Location, MessageType.Info, messagess, MessageOrigin.MES);
                            }
                            CimLogger.Debug($"{GetType().Name}.MSAccessConnect() ProbeCard Validation OK !  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                        }
                        else
                        {
                            result = "ProberCard status does not match ProberCard,Please check! ";
                            CimLogger.Warning($"{GetType().Name}.MSAccessConnect() {result}  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}, ProberCardStatus:{return_result[0].CardStatus}");

                        }
                    }
                    else
                    {
                        result = "ProductID does not match ProberCard,Please check! ";
                        CimLogger.Warning($"{GetType().Name}.MSAccessConnect() {result}-2  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                    }
                }
                else
                {
                    result = "ProductID does not match ProberCard,Please check! ";
                    CimLogger.Warning($"{GetType().Name}.MSAccessConnect() {result}-1  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                }
            }
            else
            {
                result = "ProberCard does not match EquipmentID,Please check! ";
                CimLogger.Warning($"{GetType().Name}.MSAccessConnect() 查询数据失败，Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
            }
          
            return result;

        }
        public string MSAccessByUF2000(IFreeSql fsql,string Location, string CardID, string ProductID)
        {
          
                var result = "";
                var return_result = fsql.Ado.Query<ProberCardList>("SELECT  a.[ProductID], a.[CardID] ,a.[Location],a.[CardStatus],a.[RecommendOD] FROM [ProbeCardList] a " + "where a.CardID=" + "'" + CardID + "'" + " " + "and a.Location=" + "'" + Location + "'");
                if (return_result.Count != 0 && return_result.Count == 1)
                {
                    CimLogger.Debug($"{GetType().Name}.MSAccessConnect() 查询数据成功");

                    if (ProductID.Length >= 4)
                    {

                        var productid = ProductID;//取中划线前的数据进行匹配，前面传值时就取了。
                        if (return_result[0].ProductID.Contains(productid))
                        {
                            if (return_result[0].CardStatus == "Work")
                            {
                                result = "success";
                                var messagess = TranslateMsg.GetTranslation("ProbeCardValidationOK");
                                if (messagess != null && messagess.Count != 0)
                                {
                                    EAPClientService ClientService = new EAPClientService();
                                    ClientService.ShowMessage(Location, MessageType.Info, messagess, MessageOrigin.MES);
                                }
                                CimLogger.Debug($"{GetType().Name}.MSAccessConnect() ProbeCard Validation OK !  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                                Dict.Current.RecommendOD = return_result[0].RecommendOD.ToString();
                            }
                            else
                            {
                                // result = "ProberCard status does not match ProberCard,Please check! ";
                                result = "针卡当前的状态不是Work,请检查! ";
                                CimLogger.Warning($"{GetType().Name}.MSAccessConnect() {result}  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}, ProberCardStatus:{return_result[0].CardStatus}");

                            }
                        }
                        else
                        {
                            //result = "ProductID does not match ProberCard,Please check! ";
                            result = "针卡ID与产品ID不匹配,请检查! ";
                            CimLogger.Warning($"{GetType().Name}.MSAccessConnect() {result}-2  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                        }
                    }
                    else
                    {
                        //result = "ProductID does not match ProberCard,Please check! ";
                        result = "针卡ID与产品ID不匹配,请检查! ";
                        CimLogger.Warning($"{GetType().Name}.MSAccessConnect() {result}-1  Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                    }
                }
                else
                {
                    //result = "ProberCard does not match EquipmentID,Please check! ";
                    result = "针卡ID与当前设备ID不匹配或访问针卡数据库失败,请检查! ";
                    CimLogger.Warning($"{GetType().Name}.MSAccessConnect() 查询数据失败，Location：{Location}，CardID：{CardID}，ProductID：{ProductID}");
                }

            return result;
            
        }
        public void Init()
        {
            try
            {
                var subPath = AppDomain.CurrentDomain.BaseDirectory + "DB";
                if (!System.IO.Directory.Exists(subPath))
                {
                    System.IO.Directory.CreateDirectory(subPath);
                }
                var pathInfo = Dict.Current.DataSource.Split('=').Where(t => t.Contains(@"\")).FirstOrDefault();
                var path = pathInfo.Split(';')[0];
                sPath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"DB\ProbeCardInfo.mdb");
                CimLogger.Debug($"{GetType().Name}.Init() path " + path);
                CimLogger.Debug($"{GetType().Name}.Init() sPath " + sPath);
                System.IO.File.Copy(path, sPath, true);
            }
            catch (Exception ex)
            {
                CimLogger.Error($"{GetType().Name}.Init: {ex}");
            }
        }

    }
}
